//
//  HLLoginCategoryView.m
//  YueYue
//
//  Created by hulu001 on 2023/5/23.
//

#import "HLLoginCategoryView.h"
#import "HLLoginCodeViewController.h"
#import <CL_ShanYanSDK/CL_ShanYanSDK.h>
#import <UMCommon/UMCommon.h>
#import <UMShare/UMShare.h>

typedef enum : NSUInteger {
    HLLoginCategoryTagPhoneCode = 2204,
    HLLoginCategoryTagWechat,
    HLLoginCategoryTagEmail,
    HLLoginCategoryTagPhone,
} HLLoginCategoryTag;


@interface HLLoginCategoryView ()

@property (nonatomic, strong) UILabel *sloganLabel;
@property (nonatomic, strong) UILabel *numbelLabel;
@property (nonatomic, strong) QMUIButton *otherButton;

@end


@implementation HLLoginCategoryView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = UIColorWhite;
        [self setupView];
        
    }
    return self;
}

- (void)setupView {
    
    self.layer.masksToBounds = NO;
    self.layer.cornerRadius = 12;
    
    self.protocolView = [[HLLoginAgreeProtocolView alloc] init];
    [self addSubview:_protocolView];
    [_protocolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_lessThanOrEqualTo(SCREEN_WIDTH);
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 12));
    }];
    
    self.contentView = [[UIStackView alloc] init];
    _contentView.axis = UILayoutConstraintAxisVertical;
    _contentView.alignment = UIStackViewAlignmentTop;
    _contentView.distribution = UIStackViewDistributionEqualSpacing;
    _contentView.spacing = 12;
    [self addSubview:_contentView];
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(24);
        make.right.mas_equalTo(-24);
        make.top.mas_equalTo(32);
    }];

    if (HLRunTime.shareInstance.shanYan.number.length > 0){
        [self phoneLogin];
    } else {
        [self otherLogin];
    }
    
}

- (void)otherLogin
{
    self.phoneCodeButton = [self createLoginButtonWithIcon:UIImageMake(@"login_phone_code") title:@"手机号登录" tag:HLLoginCategoryTagPhoneCode];
    _phoneCodeButton.layer.borderColor = HLMainColor.CGColor;
    [_phoneCodeButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [_phoneCodeButton setBackgroundColor:HLMainColor];
    [_contentView addArrangedSubview:_phoneCodeButton];
    
    self.phoneButton = [self createLoginButtonWithIcon:UIImageMake(@"login_phone") title:@"手机号一键登录" tag:HLLoginCategoryTagPhone];
    [_contentView addArrangedSubview:_phoneButton];
    if ([HLRunTime shareInstance].isFood) {
        return;
    }
//    self.wechatButton = [self createLoginButtonWithIcon:UIImageMake(@"login_wechat") title:@"微信登录" tag:HLLoginCategoryTagWechat];
//    [_contentView addArrangedSubview:_wechatButton];
}

- (void)phoneLogin
{
    HLShanYanModel *shanYan = [HLRunTime shareInstance].shanYan;
    
    CGFloat width = SCREEN_WIDTH-48;
    self.sloganLabel = [[UILabel alloc] qmui_initWithFont:UIFontMake(13) textColor:HLTextColor3];
    _sloganLabel.text = shanYan.slogan;
    _sloganLabel.textAlignment = NSTextAlignmentCenter;
    [_sloganLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(width);
    }];
    [_contentView addArrangedSubview:_sloganLabel];
    
    self.numbelLabel = [[UILabel alloc] qmui_initWithFont:UIFontBoldMake(26) textColor:HLTextColor1];
    _numbelLabel.text = shanYan.number;
    _numbelLabel.textAlignment = NSTextAlignmentCenter;
    [_numbelLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(width);
    }];
    [_contentView addArrangedSubview:_numbelLabel];
    
    
    self.phoneButton = [self createLoginButtonWithIcon:nil title:@"手机号一键登录" tag:HLLoginCategoryTagPhone];
    _phoneButton.layer.borderColor = HLMainColor.CGColor;
    [_phoneButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [_phoneButton setBackgroundColor:HLMainColor];
    [_contentView addArrangedSubview:_phoneButton];
    
    self.otherButton = [[QMUIButton alloc] init];
    [_otherButton setImage:UIImageMake(@"mine_arrow_icon") forState:UIControlStateNormal];
    [_otherButton setTitle:@"其他方式登录" forState:UIControlStateNormal];
    [_otherButton setTitleColor:HLTextColor2 forState:UIControlStateNormal];
    [_otherButton.titleLabel setFont:UIFontMake(12)];
    [_otherButton addTarget:self action:@selector(changeLoginAction) forControlEvents:UIControlEventTouchUpInside];
    _otherButton.imagePosition = QMUIButtonImagePositionRight;
    _otherButton.spacingBetweenImageAndTitle = 1;
    [_otherButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(width);
    }];
    [_contentView addArrangedSubview:_otherButton];
}


- (QMUIButton *)createLoginButtonWithIcon:(nullable UIImage  *)icon title:(NSString *)title tag:(NSInteger)tag
{
    QMUIButton *loginButton = [[QMUIButton alloc] init];
    [loginButton setTitleColor:HLTextColor1 forState:UIControlStateNormal];
    [loginButton setTitle:title forState:UIControlStateNormal];
    [loginButton setBackgroundColor:UIColorWhite];
    [loginButton.titleLabel setFont:UIFontMediumMake(16)];
    loginButton.layer.borderColor = HLTextColor1.CGColor;
    loginButton.layer.borderWidth = 1;
    loginButton.tag = tag;
    [loginButton setCornerRadius:12];
    [loginButton setContentEdgeInsets:UIEdgeInsetsMake(15, 20, 15, 20)];
    [loginButton addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:icon];
    imageView.userInteractionEnabled = NO;
    [loginButton addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.centerY.mas_equalTo(0);
    }];
    [loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-48, 50));
    }];
    return loginButton;
}

- (void)loginAction:(QMUIButton *)btn
{
    if (!_protocolView.agreeButton.isSelected){
        MJWeakSelf
        [HLUIHelper showAlertMustAgreeProtocalWithCallback:^(BOOL isCheck) {
            if (isCheck){
                weakSelf.protocolView.agreeButton.selected = YES;
                [weakSelf pushAction:btn];
            }
        }];
        return;
    }
    
    [self pushAction:btn];
}

- (void)pushAction:(QMUIButton *)btn
{
    switch (btn.tag) {
        case HLLoginCategoryTagPhoneCode:
            [self loginPhoneCode];
            break;
        case HLLoginCategoryTagWechat:
            [self loginWithWechat];
            break;
        case HLLoginCategoryTagPhone:
            if (HLRunTime.shareInstance.shanYan.number.length > 0){
                [self loginPhone];
            } else {
                [HLHelper shanYanLoadWithCallback:^{
                    dispatch_sync(dispatch_get_main_queue(), ^{
                        if (HLRunTime.shareInstance.shanYan.number.length > 0){
                            [self loginPhone];
                        } else {
                            [QMUITips showWithText:@"无法识别SIM卡或没有SIM卡"];
                        }
                    });
                }];
            }
 
            break;
    }
}


- (void)changeLoginAction
{
    _sloganLabel.hidden = YES;
    _numbelLabel.hidden = YES;
    _phoneButton.hidden = YES;
    _otherButton.hidden = YES;
    [_contentView removeArrangedSubview:_sloganLabel];
    [_contentView removeArrangedSubview:_numbelLabel];
    [_contentView removeArrangedSubview:_phoneButton];
    [_contentView removeArrangedSubview:_otherButton];
    [self otherLogin];
}

- (void)loginPhoneCode
{
    HLLoginCodeViewController *loginCodeVC = [[HLLoginCodeViewController alloc] init];
    [self.qmui_viewController.navigationController pushViewController:loginCodeVC animated:YES];
}

- (void)loginPhone
{
    
    CLUIConfigure *baseUIConfigure = [self configureMake];
    [CLShanYanSDKManager quickAuthLoginWithConfigure:baseUIConfigure openLoginAuthListener:^(CLCompleteResult * _Nonnull completeResult) {
        // hide loading...
        if (completeResult.error) {
            //拉起授权页失败
            [QMUIConsole log:[NSString stringWithFormat:@"openLoginAuthListener:%@",completeResult.error.userInfo]];
        }else{
            //拉起授权页成功
            //NSLog(@"openLoginAuthListener:%@",completeResult.yy_modelToJSONObject);
        }
    } oneKeyLoginListener:^(CLCompleteResult * _Nonnull completeResult) {
        
        if (completeResult.error) {
            //一键登录失败
            [QMUIConsole log:[NSString stringWithFormat:@"oneKeyLoginListener:%@",completeResult.error.description]];
            
            //提示：错误无需提示给用户，可以在用户无感知的状态下直接切换登录方式
            if (completeResult.code == 1011){
                //用户取消登录（点返回）
                //处理建议：如无特殊需求可不做处理，仅作为交互状态回调，此时已经回到当前用户自己的页面
                //点击sdk自带的返回，无论是否设置手动销毁，授权页面都会强制关闭
            }  else{
                [QMUITips showWithText:[NSString stringWithFormat:@"一键登录报错 %ld", completeResult.error.code]];
                [CLShanYanSDKManager finishAuthControllerCompletion:nil];
            }
        }else{
            dispatch_sync(dispatch_get_main_queue(), ^{
                NSString *token = completeResult.data[@"token"];
                NSDictionary *params = @{
                    @"token":token,
                    @"loginType":@"2"};
                [HLUIHelper loginWithParams:params];
            });
        }
    }];
}

- (void)loginWithWechat
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:UMSocialPlatformType_WechatSession currentViewController:self.qmui_viewController completion:^(id result, NSError *error) {
        if (error){
            NSString *msg = error.localizedDescription;
            if (msg.length == 0){
                msg = @"登录失败";
            }
            [QMUITips showWithText:msg];
            return;
        }
        UMSocialUserInfoResponse *resp = result;
        NSDictionary *params = @{
            @"unionId":resp.unionId,
            @"loginType":@"4"};
        [HLUIHelper loginWithParams:params];
    }];
}



-(CLUIConfigure *)configureMake{
    
    
    CLUIConfigure *configure = [[CLUIConfigure alloc] init];
    configure.viewController = self.qmui_viewController;
    configure.shouldAutorotate = @(NO);
    configure.clNavigationBarHidden = @(YES);
    
    configure.clSloganTextFont = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];
    configure.clSloganTextColor = HLTextColor1;
    configure.clSlogaTextAlignment = @(NSTextAlignmentCenter);
    
    //手机号
    configure.clPhoneNumberColor = HLTextColor1;
    configure.clPhoneNumberFont = [UIFont systemFontOfSize:30 weight:UIFontWeightMedium];
    configure.clPhoneNumberTextAlignment = @(NSTextAlignmentCenter);
    
    configure.clLoginBtnBgColor = HLMainColor;
    configure.clLoginBtnTextFont = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    configure.clLoginBtnTextColor = UIColor.whiteColor;
    configure.clLoginBtnText = @"下一步";
    configure.clLoginBtnCornerRadius = @(28);
    
    
    configure.clAppPrivacyColor = @[HLTextColor3,HLMainColor];
    configure.clAppPrivacyTextFont = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];
    configure.clAppPrivacyNormalDesTextFirst = @"我已阅读并同意";
    
    configure.clAppPrivacyFirst = @[@"用户服务协议",[NSURL URLWithString:HLH5ProtocolUserUrl]];
    configure.clOperatorPrivacyAtLast = @(YES);
    configure.clAppPrivacyNormalDesTextLast = @"";
    configure.clCheckBoxVerticalAlignmentOffset = @(-3);
    
    configure.clCheckBoxUncheckedImage = UIImageMake(@"login_unchecked");
    configure.clCheckBoxCheckedImage = UIImageMake(@"login_checked");
    
    CLOrientationLayOut *layOut = [[CLOrientationLayOut alloc] init];
    
    
    //手机号
    layOut.clLayoutPhoneTop = @(NavigationContentTopConstant+160);
    layOut.clLayoutPhoneLeft = @(0);
    layOut.clLayoutPhoneRight = @(0);
    layOut.clLayoutPhoneWidth = @(SCREEN_WIDTH);
    layOut.clLayoutPhoneHeight = @(25);
    CGFloat h = layOut.clLayoutSloganHeight.floatValue+NavigationContentTopConstant+160+20;
    
    //运营商
    layOut.clLayoutSloganLeft = @(0);
    layOut.clLayoutSloganRight = @(0);
    layOut.clLayoutSloganWidth = @(SCREEN_WIDTH);
    layOut.clLayoutSloganTop = @(h+20);
    layOut.clLayoutSloganHeight = @(20);
    
    
    //登录按钮
    layOut.clLayoutLoginBtnTop = @(h+60);
    layOut.clLayoutLoginBtnLeft = @(40);
    layOut.clLayoutLoginBtnRight = @(-40);
    layOut.clLayoutLoginBtnHeight = @(56);
    
    //隐私条款
    layOut.clLayoutAppPrivacyLeft = @(40);
    layOut.clLayoutAppPrivacyRight = @(-40);
    layOut.clLayoutAppPrivacyTop = @(h+150);
    layOut.clLayoutAppPrivacyCenterX = @(0);
//    layOut.clLayoutAppPrivacyHeight = @(50);
    
   
    
    configure.customAreaView = ^(UIView * _Nonnull customAreaView) {
        
        QMUIButton *popBtn = [QMUIButton.alloc init];
        [popBtn setImage:UIImageMake(@"nav_back_black") forState:UIControlStateNormal];
        [customAreaView addSubview:popBtn];
        [popBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(5);
            make.top.mas_equalTo(StatusBarHeightConstant + 5);
            make.size.mas_equalTo(44);
        }];
        
        [popBtn setQmui_tapBlock:^(__kindof UIControl *sender) {
            [CLShanYanSDKManager finishAuthControllerCompletion:nil];
        }];
        
        
        UILabel *titleLabel = [[UILabel alloc] qmui_initWithFont:UIFontMediumMake(24) textColor:HLTextColor1];
        titleLabel.text = @"你好，\n欢迎来到越轻食";
        titleLabel.numberOfLines = 0;
        [customAreaView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(16);
            make.right.mas_equalTo(-16);
            make.top.mas_equalTo(NavigationContentTopConstant + 12);
        }];

    };
    
    configure.clOrientationLayOutPortrait = layOut;
    
    return configure;
}

@end
